{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import shutil\n",
    "import os\n",
    "\n",
    "folder_path = \"/hy-tmp/new_uspto_mol\"\n",
    "\n",
    "# 强制删除文件夹及其内容\n",
    "shutil.rmtree(folder_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import os\n",
    "\n",
    "from PIL import Image\n",
    "import random\n",
    "# 读取CSV文件\n",
    "df = pd.read_csv(\"../new_uspto_mol/new_uspto_mol/uspto_mol/new_train1.csv\")\n",
    "# 随机抽取数据集的子集\n",
    "sample_size = 4  # 你想要抽取的数据量\n",
    "sampled_df = df.sample(n=sample_size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 创建一个新的文件夹来保存抽取的图片\n",
    "image_folder = '../new_uspto_mol/new_uspto_mol/'\n",
    "if not os.path.exists(image_folder):\n",
    "    os.makedirs(image_folder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 遍历抽取的数据，并提取图片\n",
    "base_image_path = \"../new_uspto_mol/new_uspto_mol/\"\n",
    "for index, row in sampled_df.iterrows():\n",
    "    image_path = row['file_path']  # 替换为你的图片路径列名\n",
    "    relative_path = os.path.dirname(image_path) #这里是只提取文件夹的路径，而不包括具体文件的名称，\n",
    "    # 因为到时候创建文件夹时会把文件名也当作一个文件夹创建\n",
    "    save_path = os.path.join(image_folder, relative_path) #按图片原路径结构存储\n",
    "    if not os.path.exists(save_path):\n",
    "        os.makedirs(save_path)\n",
    "\n",
    "    if os.path.exists(save_path):\n",
    "        # 如果原图片路径没创建就不读取图片了\n",
    "        image_path = os.path.join(base_image_path, image_path)\n",
    "    image = Image.open(image_path)\n",
    "    # 保存图片到新的文件夹\n",
    "    image.save(os.path.join(save_path, os.path.basename(image_path)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 保存新的CSV文件\n",
    "sampled_df.to_csv('../new_uspto_mol/new_uspto_mol/uspto_mol/new_train.csv', index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
